package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrSequenceOf;
import org.road0329.dlt698.opt.SubSeqOfSets;

import java.io.IOException;

public class ProxySetRequestList {
    private byte[] dataCode = null;
    private PIID piid = null;
    private Unsigned16 waitTime = null;
    private SubSeqOfSets sets = null;

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    public void setAll(PIID piid, Unsigned16 waitTime, SubSeqOfSets sets) {
        this.piid = piid;
        this.waitTime = waitTime;
        this.sets = sets;
    }

    public void setPiid(PIID piid) {
        this.piid = piid;
    }

    public void setWaitTime(Unsigned16 waitTime) {
        this.waitTime = waitTime;
    }

    public void setSets(SubSeqOfSets sets) {
        this.sets = sets;
    }

    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.piid = new PIID();
        // Assuming setNumBit and decode methods exist in PIID
        this.piid.setNumBit(8);
        codeLength += this.piid.decode(input);
        this.waitTime = new Unsigned16();
        // Assuming set_const and decode methods exist in Unsigned16
        this.waitTime.setConst();
        codeLength += this.waitTime.decode(input);
        this.sets = new SubSeqOfSets();
        codeLength += this.sets.decode(input);
        return codeLength;
    }

    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength;
        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (int i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if (this.sets != null && this.waitTime != null && this.piid != null) {
                codeLength = 0;
                codeLength += this.sets.encode(output);
                codeLength += this.waitTime.encode(output);
                codeLength += this.piid.encode(output);
            } else {
                throw new RuntimeException("sets || waitTime || piid is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.toByteArray();
    }

    @Override
    public String toString() {
        if (this.piid != null && this.waitTime != null && this.sets != null) {
            return "sequence: {" + "piid: " + this.piid + ", waittime: " + this.waitTime + ", sets: " + this.sets + "}";
        } else {
            return "sets || waitTime || piid is null";
        }
    }
}



